package login

import (
	"context"
	"errors"
	"go_zero_blog/common/helper"
	"go_zero_blog/common/xerr"
	"go_zero_blog/models"
	"gorm.io/gorm"

	"go_zero_blog/internal/svc"
	"go_zero_blog/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginRes, err error) {
	var info types.User
	if err = l.svcCtx.DB.Model(&models.User{}).Where("username = ? and password = ?", req.Username, helper.SaltedMd5(req.Password, "go_zero_blog")).First(&info).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, xerr.NewErrCode(xerr.UserNotExistError)
		}
		return nil, xerr.NewErrCode(xerr.DBError)
	} else {
		token, _ := helper.GenerateJwtToken(
			&helper.CustomJwtClaims{
				Uid:      info.Uid,
				Username: info.Username,
			},
			l.svcCtx.Config.Auth.AccessSecret,
			l.svcCtx.Config.Auth.AccessExpire,
		)
		return &types.LoginRes{
			Info:  info,
			Token: token,
		}, nil
	}
}
